package cn.nawang.ebeim.persist.dao;

import cn.nawang.ebeim.persist.constants.InitSql;
import cn.nawang.ebeim.persist.domain.DataSource;
import cn.nawang.ebeim.persist.handler.BeanListHandler;
import cn.nawang.ebeim.persist.utils.DBPool;
import cn.nawang.ebeim.persist.utils.DBUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by GanJc on 2016/2/1.
 */
public class DataSourceDaoImpl implements DataSourceDao {


    public DataSourceDaoImpl() {
        initDB();
    }

    public void initDB()  {
        try {
            DBUtils.execute(getConnection(), InitSql.CREATE_DATA_SOURCE_TABLE, null);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    public Connection getConnection() {
        return  DBPool.getInstance().getConnection(InitSql.URL, "", "");
    }

    public void saveDataSource(DataSource dataSource) {
        System.out.println("saveDataSource:" + dataSource);

        String sql = "insert into data_source(root_path,dsId,abs_path,total_dir,total_file,create_time) values(?,?,?,?,?,?)";
        Object[] params = {dataSource.getRootPath(), dataSource.getDsId(),dataSource.getAbsPath(), dataSource.getTotalDir(), dataSource.getTotalFile(),System.currentTimeMillis()};
        try {
            DBUtils.execute(getConnection(), sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<DataSource> findDataSources() {
        List list = null;
        String sql = "select * from data_source ";
        BeanListHandler rsh = new BeanListHandler(DataSource.class);
        try {
            list = (List) DBUtils.find(getConnection(),sql, null, rsh);
        } catch (Exception e) {
            System.out.println("读取数据库异常,异常信息:"+e.getMessage());
        }
        return list;
    }

}
